#!/usr/bin/python
# -*- coding: utf8 -*-

import sys, os
import time, traceback, platform
from pathlib import Path as p


def get_max_common_prefix(target_files_stem):
    prefix_idx = 0
    min_len = min([len(fi) for fi in target_files_stem])
    cur_char = None
    for i in range(min_len):
        all_same = True
        for tfs in target_files_stem:
            if cur_char is None:
                cur_char = tfs[prefix_idx]
            elif tfs[prefix_idx] != cur_char:
                all_same = False
                break
        if all_same:
            prefix_idx = i + 1
        else:
            break
        cur_char = None

    print('prefix:', target_files_stem[0][0:prefix_idx])
    return prefix_idx

try:

    dir_path = p(sys.argv[1]).absolute()
    print("工作目录：", dir_path)
    target_files = [f for f in p(dir_path).iterdir() if p(f).is_file() and f.suffix != '.torrent']

    suffix_idx = 0

    if len(target_files) <= 1:
        print('没有文件可以重命名！')
        sys.exit(1)

    target_files_stem = [f.stem for f in target_files]

    prefix_idx = get_max_common_prefix(target_files_stem)

    target_files_stem_reversed = [st[::-1] for st in target_files_stem]

    suffix_idx = get_max_common_prefix(target_files_stem_reversed)

    for tf in target_files:
        old_name = tf.name
        new_stem = tf.name[prefix_idx:len(tf.stem)-suffix_idx]
        if len(new_stem) == 1 and new_stem.isdigit():
            new_stem = '0' + new_stem
        new_file = tf.with_stem(new_stem)
        print(tf.name, ' ==> ', new_file.name)
        tf.rename(new_file)

except:
    traceback.print_exc()

os.system('pause')